package com.woniu.service;

import ch.qos.logback.classic.Logger;
import com.woniu.adapter.CouponAdapter;
import com.woniu.adapter.UserCouponAdapter;
import com.woniu.exception.CouponException;
import com.woniu.exception.UserCouponException;
import com.woniu.inlet.web.fo.CouponFo;
import com.woniu.outlet.client.UserCenterClient;
import com.woniu.outlet.mysql.dao.UserCouponDao;
import com.woniu.outlet.mysql.po.Coupon;
import com.woniu.outlet.mysql.po.CouponExample;
import com.woniu.outlet.mysql.po.UserCoupon;
import com.woniu.outlet.mysql.po.UserCouponExample;
import com.woniu.service.command.*;
import com.woniu.service.domain.CouponDto;
import com.woniu.utils.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

@Service
@Slf4j
public class CouponService implements AddCouponCommandHandle,
        DistributeCommandHandle, CouponPayCommandHandle, UpdateUserCouponCommandHandle {
    @Autowired
    private CouponAdapter couponAdapter;

    @Autowired
    private UserCouponAdapter userCouponAdapter;

    @Autowired
    private UserCenterClient userCenterClient;

    @Autowired
    private UserCouponDao userCouponDao;

    //管理员添加优惠券
    @Override
    public void addCoupon(AddCouponCommand addCouponCommand) {
        if (AppUtils.isNullCouponFo(addCouponCommand.getCouponFo())) {
            throw new CouponException("参数不能为空");
        }

        CouponDto couponDto = new CouponDto();
        BeanUtils.copyProperties(addCouponCommand.getCouponFo(), couponDto);
        log.debug("进入添加couponDto对象为[{}]", couponDto);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(addCouponCommand.getCouponFo().getCreateTime());
        } catch (ParseException e) {
            e.printStackTrace();
            throw new CouponException("输入的时间格式有误！！！");
        }
        //设置截止日期
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(calendar.DATE, couponDto.getValidity());
        date = calendar.getTime();//获得截止时间
        couponDto.setDeadline(sdf.format(date));

        log.debug("将要添加的couponDto对象是[{}]", couponDto);
        couponAdapter.add(couponDto);

    }

    //管理员分发优惠券
    @Override
    @Transactional
    public void distributeCoupon(DistributeCommand command) {
        if (command.getCouponId() == null || command.getUserIds().isEmpty()) {
            throw new UserCouponException("参数不符合要求");
        }
        Coupon coupon = couponAdapter.getById(command.getCouponId());
        if (coupon == null) {
            throw new UserCouponException("未查询到该优惠券");
        }
        log.debug("要添加的优惠券是[{}]", coupon);
        //查询用户id是都存在

        boolean exist = userCenterClient.isExist(command.getUserIds());
        log.debug("查询用户是否存在[{}]", exist);
        if (!exist) {
            throw new UserCouponException("添加的用户列表有误！");
        }

        //给用户分发优惠券
        for (Integer userId : command.getUserIds()) {
            UserCoupon userCoupon = new UserCoupon();
            userCoupon.setCouponId(command.getCouponId());
            userCoupon.setUserId(userId);
            userCoupon.setStatus(0);
            userCouponAdapter.insert(userCoupon);
        }
    }

    //支付时查询可用的优惠券
    @Override
    public List<UserCoupon> checkCoupon(CouponPayCommand command) {
        if (command.getUserId() == null || command.getMoney() == null) {
            throw new UserCouponException("参数不能为空");
        }
        //查询满足条件的优惠券
        String current = AppUtils.getNowTimeStr();
        List<UserCoupon> couponPay = userCouponAdapter.getCouponPay(current, command.getMoney(), command.getUserId());
        if (couponPay == null) {
            throw new UserCouponException("未查询到满足条件的优惠券");
        }
        return couponPay;
    }

    @Override
    public void updateStatus(UpdateUserCouponCommand command) {
        UserCoupon userCoupon = userCouponAdapter.getById(command.getId());
        if (userCoupon == null) {
            throw new UserCouponException("没有该优惠券");
        }
        //更新用户优惠券状态
        userCoupon.setStatus(1);
        userCouponDao.updateByPrimaryKeySelective(userCoupon);
    }

    //根据用户优惠券关联表的id查询
    public UserCoupon getUsercouponById(Integer id) {
        UserCoupon userCoupon = userCouponDao.selectByPrimaryKey(id);
        log.debug("根据用户优惠券关联表id查询到的对象为：[{}]", userCoupon);
        return userCoupon;
    }
}
